package com.student.tools;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class MyUpload {
	private static final String UPLOAD_DIRECTORY = "images/student_head_image/";
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
	private HttpServletRequest request;
	private String prefix;
	
	public MyUpload(HttpServletRequest request, String prefix) {
		this.request = request;
		this.prefix = prefix;
	}
	
	public void upload() {
		if ( !ServletFileUpload.isMultipartContent(request) )
		{
			System.out.println("Error: 表单必须包含 enctype=multipart/form-data");
		}
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(MEMORY_THRESHOLD);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setFileSizeMax(MAX_REQUEST_SIZE);
		String uploadPath = request.getServletContext().getRealPath("/") + UPLOAD_DIRECTORY;
		
		// 核心步骤
		try {
			List<FileItem> formItems = upload.parseRequest(request);
			if ( formItems != null && formItems.size() > 0 )
			{
				for ( FileItem item : formItems )
				{
					if ( !item.isFormField() )
					{
						String fileName = new File(item.getName()).getName();
						String filePath = uploadPath + File.separator + prefix + "_" + fileName;
						File storeFile = new File(filePath);
						item.write(storeFile);
						System.out.println("文件上传成功！");
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
